module executor.authorize.server.AuthorizeExecutor;

import std.stdio;
import msgtrans;
import message.Constants;
import message.MsgDefine;
import google.protobuf;
import hunt.logging;
import hunt.util.Serialize;
import client.MsgServerClient;
import client.ImClient;
import client.LogicServerClient;
import std.array;
import std.conv : to;
import core.stdc.time;
import command.StartAppCommand;
import core.stdc.string;

@TransportServer(gateServerName)
class AuthorizeExecutor : AbstractExecutor!(AuthorizeExecutor){

  @MessageId(MESSAGE.CMD_AUTHORIZE_REQ)
  void authorize(TransportContext ctx, MessageBuffer buffer) {
    auto req = new AuthenticateREQ();
    buffer.data.fromProtobuf!AuthenticateREQ(req);
    logInfo("authorizeReq : %d  --- %s -- %s " ,ctx.id ,req.accessToken);
    //logInfo("tagId : %s", buffer.extend.tagId);
    req.clientId = cast(long)ctx.id();

    TransportSession session = gateServer.sessionManager().get(req.clientId);
    //logInfo("authorizeRes session id :%d",res.clientId);

    /**
      将连接来源保存到session中 IOS ANDROID MAC
    **/



    if (session !is null)
    {
        session.setAttribute(SESSIONKEY.SRC, req);
        AuthenticateRES res = cast(AuthenticateRES)(session.getAttribute(SESSIONKEY.LOGINMSG));
        if (res !is null)
        {
          logWarning("repet login %s ", res.clientId);
          ctx.session.send(new MessageBuffer(MESSAGE.CMD_AUTHORIZE_RES,res.toProtobuf.array));
          return;
        }
    }

    LogicServerClient.getInstance().getForwardClient.send(new MessageBuffer(MESSAGE.CMD_AUTHORIZE_REQ,req.toProtobuf.array));
  }


  @MessageId(MESSAGE.CMD_SEND_DEVICE_TOKEN)
  void deviceToken(TransportContext ctx, MessageBuffer buffer) {
    auto req = new SendDeviceToken();
    buffer.data.fromProtobuf!SendDeviceToken(req);

    logInfof("Device Token: %s", req.token);

    User u = cast(User)ctx.session.getAttribute(SESSIONKEY.USER);
    AuthenticateREQ authorize = cast(AuthenticateREQ)ctx.session.getAttribute(SESSIONKEY.SRC);

    ServerExtend serverExtend;

    /**
        如果已经登录过,则从session里取userid打包到扩展字段里发送给logicserver
    **/

    if(u !is null)
    {
      req.src = authorize.src;
      serverExtend.userId = to!ulong(u.id);
      ubyte[ServerExtend.sizeof] extend ;
      memcpy(extend.ptr,&serverExtend,ServerExtend.sizeof);
      LogicServerClient.getInstance().getForwardClient.send(new MessageBuffer(MESSAGE.CMD_SEND_DEVICE_TOKEN,req.toProtobuf.array,extend));
    }

  }
}

